package com.eastfair.pay.chinaums.common.utils;



import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class SignUtil {

    public static String getSignHeader(String appid,String appkey,String timestamp,String nonce,String body) throws Exception {
        String localSignatureStr = getSignString(appid,appkey,timestamp,nonce,body);
        String signHeader = "OPEN-BODY-SIG AppId="+"\""+appid+"\""+", Timestamp="+"\""+timestamp+"\""+", Nonce="+"\""+nonce+"\""+", Signature="+"\""+localSignatureStr+"\"";
        return signHeader;
    }

    public static String getSignString(String appid,String appkey,String timestamp,String nonce,String body) throws Exception {
        byte[] data = body.getBytes("utf-8");
        InputStream is = new ByteArrayInputStream(data);
        String s1 = appid+timestamp+nonce+testSHA256(is);
        byte[] localSignature = hmacSHA256(s1.getBytes(), appkey.getBytes("utf-8"));
        String localSignatureStr = Base64.encodeBase64String(localSignature);
        return localSignatureStr;
    }

    public static byte[] hmacSHA256(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException {
        String algorithm = "HmacSHA256";
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key, algorithm));
        return mac.doFinal(data);
    }
    private static String testSHA256(InputStream is){
        try {
            System.out.println(is.hashCode());
            return DigestUtils.sha256Hex(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getSHA1(String s){
        System.out.println(s);
        return DigestUtils.sha1Hex(s);
        //return Base64.encodeBase64String(DigestUtils.sha1(s));
    }
}
